extends Node2D

@export var bgm: AudioStream

@onready var playerScene: Player = $Player
@onready var hand: Hand = $BattleUI/Hand
@onready var endTurnBtn: Button = %EndTurn
@onready var enemies: Enemies = $Enemies

# 抽卡间隔时间
const DRAW_INTERVAL := 0.25

var player: PlayerStatsSrc

func _ready():
	init()
	startBattle()

# 场景初始化-信号连接等
func init():
	get_tree().paused = false
	player = playerScene.statsSrc
	endTurnBtn.pressed.connect(turnEnd)
	Events.cardPlayed.connect(cardPlayed)
	Events.enemyTurnEnd.connect(startTurn)
	Events.turnEnd.connect(enemies.startTurn)
	Events.died.connect(playerDied)
	enemies.child_order_changed.connect(enemiesChange)
	MusicPlayer.play(bgm, 1)
	Game.battleOver.hide()

# 开始战斗
func startBattle() -> void:
	player.drawcards = player.deck.duplicate(true)
	player.drawcards.shuffle()
	player.discard.clear()
	startTurn()

# 回合开始
func startTurn() -> void:
	enemies.resetActions()
	player.armor = 0
	player.resetEnergy()
	drawCards(player.drawNum)

# 抽一张牌
func drawCard() -> void:
	reshuffle()
	hand.addCard(player.drawcards.draw())

# 抽牌堆为空时，将弃牌堆重洗牌并加入抽牌堆
func reshuffle() -> void:
	if !player.drawcards.isEmpty(): return
	# 将所有弃牌堆的卡加入抽牌堆
	while !player.discard.isEmpty():
		player.drawcards.addCard(player.discard.draw())
	player.drawcards.shuffle()

# 抽多张牌
func drawCards(num: int) -> void:
	var tween := create_tween()
	for i in range(num):
		tween.tween_callback(drawCard)
		tween.tween_interval(DRAW_INTERVAL)
	tween.finished.connect(
		func(): endTurnBtn.disabled=false
	)

# 打出一张卡牌
func cardPlayed(cardSrc: CardSrc) -> void:
	player.discard.addCard(cardSrc)

# 弃手牌
func discardHand() -> void:
	var tween := create_tween()
	for card in hand.get_children():
		# 卡牌加入弃牌堆
		tween.tween_callback(player.discard.addCard.bind(card.cardSrc))
		tween.tween_callback(hand.discard.bind(card))
		tween.tween_interval(DRAW_INTERVAL)
	# 手牌弃完回合结束
	tween.finished.connect(
		func(): Events.turnEnd.emit()
	)

# 回合结束
func turnEnd() -> void:
	endTurnBtn.disabled = true
	hand.disableHand()
	discardHand()

# 监听敌人数量变化
func enemiesChange() -> void:
	if enemies.get_child_count() == 0:
		Game.battleOver.showScreen('游戏胜利', Game.battleOver.Type.WIN)

# 玩家死亡
func playerDied() -> void:
	Game.battleOver.showScreen('游戏失败', Game.battleOver.Type.LOSE)
